package com.ourteam.workspace.api;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;
import org.apache.velocity.app.VelocityEngine;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ourteam.frame.controller.AbstractCRUDServiceController;
import com.ourteam.frame.web.OperationResult;
import com.ourteam.frame.web.ProgressInfoBean;
import com.ourteam.frame.web.RequestStatus;
import com.ourteam.product.ui.domain.ProductUIPageBean;
import com.ourteam.product.ui.service.IProductUIService;
import com.ourteam.product.ui.service.ProductUIServiceFactory;
import com.ourteam.scm.utils.DefaultSCMListener;
import com.ourteam.scm.utils.ISCMService;
import com.ourteam.scm.utils.ModuleInfoBean;
import com.ourteam.workspace.dao.WorkspaceResourceUIPageRelateDAOQueryBean;
import com.ourteam.workspace.domain.WorkspaceBean;
import com.ourteam.workspace.domain.WorkspaceResourceUIPageRelateBean;
import com.ourteam.workspace.domain.WorkspaceScmConfigBean;
import com.ourteam.workspace.service.IWorkspaceService;
import com.ourteam.workspace.service.WorkspaceServiceFactory;

@Controller
@RequestMapping("/api/WORKSPACE/ProductUIPageRelate")
public class ResourceRelatedUIPageAPI extends

		AbstractCRUDServiceController<WorkspaceResourceUIPageRelateDAOQueryBean, ResourceRelatedUIPageSearchModel, WorkspaceResourceUIPageRelateBean> {

	private static final IWorkspaceService WORKSPACE_SERVICE = WorkspaceServiceFactory.getWorkspaceService();

	private static final IProductUIService PRODUCT_UI_SERVICE = ProductUIServiceFactory.getProductUIService();

	@Override
	protected WorkspaceResourceUIPageRelateDAOQueryBean newQueryBean() {
		return new WorkspaceResourceUIPageRelateDAOQueryBean();
	}

	@Override
	protected int queryCount(WorkspaceResourceUIPageRelateDAOQueryBean queryBean) throws Exception {
		return WORKSPACE_SERVICE.queryWorkspaceResourceUIPageRelateCount(queryBean);
	}

	@Override
	protected WorkspaceResourceUIPageRelateBean[] queryData(WorkspaceResourceUIPageRelateDAOQueryBean queryBean)
			throws Exception {
		return WORKSPACE_SERVICE.queryWorkspaceResourceUIPageRelates(queryBean);
	}

	@Override
	protected void deleteData(long[] ids) throws Exception {
		WORKSPACE_SERVICE.deleteWorkspaceResourceUIPageRelates(ids);
	}

	@Override
	protected WorkspaceResourceUIPageRelateBean getDataById(long id) throws Exception {
		return WORKSPACE_SERVICE.getWorkspaceResourceUIPageRelateById(id);
	}

	@Override
	protected void saveData(WorkspaceResourceUIPageRelateBean dataBean) throws Exception {
		dataBean.setSubmitterId(getLoginUserId());
		dataBean.setSubmitterName(getLoginUserName());
		if (dataBean.getId() == 0) {
			WORKSPACE_SERVICE.addNewWorkspaceResourceUIPageRelate(dataBean);
		} else {
			WORKSPACE_SERVICE.modifyWorkspaceResourceUIPageRelate(dataBean);
		}
	}

	@RequestMapping("addWorkspaceResourceUIPages")
	@ResponseBody
	public OperationResult addWorkspaceResourceUIPages(@RequestParam long workspaceResourceId,
			@RequestParam(value = "uiPageIds") long[] uiPageIds) throws Exception {
		WORKSPACE_SERVICE.addWorkspaceResourceUIPages(workspaceResourceId, uiPageIds);
		return OperationResult.SUCCESS_RESULT;
	}

	@RequestMapping("/checkGenWorkspaceResourceSourceCode")
	@ResponseBody
	public ProgressInfoBean checkGenWorkspaceResourceSourceCode(@RequestParam long workspaceId,
			final HttpServletRequest request) throws Exception {

		return (ProgressInfoBean) request.getSession().getAttribute("genResourceCode" + workspaceId);

	}

	@RequestMapping("/genWorkspaceResourceSourceCode")
	@ResponseBody
	public RequestStatus genWorkspaceResourceSourceCode(@RequestParam long workspaceId,
			@RequestParam(required = false, name = "uiPageIds") long[] uiPageIds, final HttpServletRequest request)
			throws Exception {

		final RequestStatus requestStatus = new RequestStatus();

		final ProgressInfoBean progressInfoBean = new ProgressInfoBean();

		WorkspaceBean workspaceBean = WORKSPACE_SERVICE.getWorkspaceById(workspaceId);

		WorkspaceScmConfigBean scmConfigBean = WORKSPACE_SERVICE.getWorkspaceScmConfig(workspaceId);

		ISCMService scmServer = WorkspaceUtils.getSCMService(scmConfigBean);

		ModuleInfoBean moduleInfo = WorkspaceUtils.getModuleInfo(scmConfigBean);

		File workspaceDir = new File(SystemUtils.USER_HOME,
				this.getConfig("workspace.rootDir") + workspaceBean.getWorkspacePath());

		if (workspaceDir.exists() == false) {
			workspaceDir.mkdirs();
		}

		progressInfoBean.setId("genResourceCode" + workspaceId);

		progressInfoBean.setTask("更新工作区代码");

		request.getSession().setAttribute(progressInfoBean.getId(), progressInfoBean);

		try {

			scmServer.updateResource(workspaceDir, moduleInfo, new DefaultSCMListener() {

				@Override
				public void logCommandLine(String arg0) {
					progressInfoBean.setProgressMessage(StringUtils.abbreviateMiddle(arg0, "...", 50));
				}

				@Override
				public void logError(String error) {
					progressInfoBean.setProgressMessage("更新工作区代码错误:" + error);
				}

			});

		} catch (Exception e) {

			requestStatus.setFinished(true);

			requestStatus.setSuccess(false);

			requestStatus.setMessage(e.getMessage());

			request.getSession().removeAttribute(progressInfoBean.getId());

			return requestStatus;
		}

		progressInfoBean.setTask("生成代码");

		requestStatus.setRequestId(progressInfoBean.getId());

		VelocityEngine velocityEngine = new VelocityEngine();

		progressInfoBean.setTotalCount(uiPageIds.length);

		StringBuffer comment = new StringBuffer("生成");

		int progressValue = 0;

		List<File> resourceDirs = new ArrayList<>();

		WorkspaceResourceUIPageRelateBean[] relateBeans = new WorkspaceResourceUIPageRelateBean[uiPageIds.length];

		for (int j = 0; j < uiPageIds.length; j++) {

			WorkspaceResourceUIPageRelateBean pageRelateBean = WORKSPACE_SERVICE
					.getWorkspaceResourceUIPageRelateById(uiPageIds[j]);

			relateBeans[j] = pageRelateBean;

			ProductUIPageBean productUIPage = PRODUCT_UI_SERVICE.getProductUIPageById(pageRelateBean.getUiPageId());

			File resourceDir = new File(workspaceDir, pageRelateBean.getResourcePath());

			if (resourceDir.exists() == false) {
				resourceDir.mkdirs();
			}

			if (resourceDirs.contains(resourceDir) == false) {
				resourceDirs.add(resourceDir);
			}

			Map<String, Object> vmContenxt = new HashMap<>();

			if (j > 0) {
				comment.append(",");
			}
			comment.append(pageRelateBean.getPageName());

			String filePath = FilenameUtils.getPathNoEndSeparator(pageRelateBean.getPageCode());

			String fileName = FilenameUtils.getName(pageRelateBean.getPageCode());

			File pageFilePath = new File(resourceDir, filePath);

			if (pageFilePath.exists() == false) {
				pageFilePath.mkdirs();
			}

			String baseDir = "./";

			if (resourceDir.getPath().equals(pageFilePath.getPath()) == false) {
				String path = StringUtils.substringAfter(pageFilePath.getPath(), resourceDir.getPath());

				int count = StringUtils.countMatches(FilenameUtils.normalizeNoEndSeparator(path, true), "/");

				baseDir = StringUtils.repeat("../", count);

			}

			File pageFile = new File(pageFilePath, fileName);

			if (pageFile.exists() == false) {
				pageFile.createNewFile();
			}

			vmContenxt.put("basePath", baseDir);

			String pageCode = ProductUICodeGenerator.generateProductUIPagetCode(velocityEngine, productUIPage,
					vmContenxt);

			progressInfoBean.setProgressMessage(
					StringUtils.abbreviateMiddle("生成[" + productUIPage.getPageName() + "]代码...", "...", 50));

			FileUtils.write(pageFile, pageCode, "UTF-8");

			// System.out.println(pageCode);

			progressInfoBean.setValue(++progressValue);

		}

		comment.append("代码");

		progressInfoBean.setTask("提交代码");

		try {

			scmServer.commitResource(workspaceDir,resourceDirs.toArray(new File[resourceDirs.size()]), moduleInfo,
					comment.toString(), new DefaultSCMListener() {

						@Override
						public void logCommandLine(String arg0) {
							progressInfoBean.setProgressMessage(StringUtils.abbreviateMiddle(arg0, "...", 50));
						}

						@Override
						public void logError(String error) {
							progressInfoBean.setProgressMessage("提交代码错误:" + error);
						}

					});

			requestStatus.setFinished(true);

			requestStatus.setSuccess(true);

			request.getSession().removeAttribute(progressInfoBean.getId());

			Date codeGenTime = new Date();

			for (int i = 0; i < relateBeans.length; i++) {
				WorkspaceResourceUIPageRelateBean pageRelateBean = relateBeans[i];

				pageRelateBean.setLastGenCodeTime(codeGenTime);
				pageRelateBean.setSubmitterId(getLoginUserId());
				pageRelateBean.setSubmitterName(getLoginUserName());
				WORKSPACE_SERVICE.modifyWorkspaceResourceUIPageRelate(pageRelateBean);
			}
			return requestStatus;

		} catch (Exception e) {

			requestStatus.setFinished(true);

			requestStatus.setSuccess(false);

			requestStatus.setMessage(e.getMessage());

			request.getSession().removeAttribute(progressInfoBean.getId());

			return requestStatus;
		}

	}
}
